<template>
  <div class="uploadComponent">
    <el-popover
      ref="pickImgPopover"
      placement="bottom-start"
      trigger="click"
      popper-class="selectImgListPopover"
      @hide="handelHide"
      :disabled="(!isMyCaeate && !isOtherDesiger) || !canEdit"
    >
      <div class="imgList">
        <div class="header">
          <div class="title">选择图标：</div>
          <div
            class="imgBox"
            :class="{ courseImgBox: saveName == 'courseIcon' }"
          >
            <img :src="currSelectIcon" />
          </div>
          <div class="confirmBtn">
            <el-button @click="confirmSelectIcon">确定</el-button>
          </div>
        </div>
        <div class="iconList">
          <div class="uploadIcon">
            <!-- <UPLOAD/> -->
            <el-upload
              class="upload-icon"
              ref="upload"
              action="/d_api/utils/uploadfiles"
              :auto-upload="false"
              list-type="text"
              :accept="accept"
              :multiple="false"
              :on-change="handelChange"
              :http-request="uploadFiles"
            >
            </el-upload>
          </div>
          <div
            class="iconBox"
            :class="{ 'is-selectIcon': selectIndex == index }"
            v-for="(item, index) in iconList"
            :key="index"
            @click="handelSelect(item, index)"
          >
            <img :src="item" />
          </div>
        </div>
      </div>
      <div
        class="showImgBox"
        :class="{
          'imgis-disabled': (!isMyCaeate && !isOtherDesiger) || !canEdit,
        }"
        slot="reference"
      >
        <img :src="filterIMGUrl" v-if="filterIMGUrl" />
      </div>
    </el-popover>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { d_uploadmultifiles } from "@/request/upload";
import { encryptionToString } from "@/util/qetag";
import { location } from "@/util/tool";
// const UPLOAD = () => import("@/components/upload/index.vue");

export default {
  components: {
    // UPLOAD
  },
  data() {
    return {
      accept: ".jpg,.jpeg,.png",
      currSelectIcon: "", // 当前iconPath
      iconList: [], // 默认图标列表
      selectIndex: null, // 当前选择icon的索引
      timer: null, // 计时器
      localsIconPath: [], // 本地保存的已上传图标
      location: location(window),
    };
  },
  props: {
    currData: Object,
    parentIconList: Array,
    isMyCaeate: Boolean, // 是否自己创建的课程
    isOtherDesiger: Boolean, // 是否是其它课程设计师
    canEdit: Boolean, // 当前课程状态可否编辑
    saveName: String,
  },
  watch: {
    parentIconList(n, o) {
      this.iconList = [...this.localsIconPath, ...n];
      this.randomImg(n);
    },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    newFileLists() {
      return this.fileList;
    },
    filterIMGUrl() {
      let url = this.currData.iconPath;
      if (url && url.indexOf("&") !== -1) {
        return url.split(url.substring(url.lastIndexOf("&")))[0];
      } else {
        return url;
      }
    },
  },
  created() {
    // 将本地icon与默认icon合并
    this.localsIconPath = this.fetchLocalStorageIconPath();
    if (this.parentIconList)
      this.iconList = [...this.localsIconPath, ...this.parentIconList];
    // 判断是否有选择的icon
    if (this.currData.iconPath) {
      this.currSelectIcon = this.currData.iconPath;
      this.selectIndex = this.iconList.indexOf(this.currSelectIcon);
    } else {
      this.randomImg(this.iconList);
    }
  },
  methods: {
    // 随机图片
    randomImg(arr) {
      this.currSelectIcon = arr[0];
    },
    // 监听弹出框隐藏
    handelHide() {
      if (this.currData.iconPath) {
        this.currSelectIcon = this.currData.iconPath;
        this.selectIndex = this.iconList.indexOf(this.currSelectIcon);
      } else {
        this.randomImg(this.iconList);
        this.selectIndex = null;
      }
    },
    // 获取本地上传的图标
    fetchLocalStorageIconPath() {
      let localS_iconPath = JSON.parse(localStorage.getItem(this.saveName));
      if (localS_iconPath) return localS_iconPath.reverse();
      return [];
    },
    // 获取本地上传的图标 将上传的图标保存至本地
    saveIconPathToLocalStorage(item) {
      let localS_iconPath = JSON.parse(localStorage.getItem(this.saveName));
      if (!localS_iconPath) localS_iconPath = [];
      localS_iconPath.push(item);
      this.localsIconPath = localS_iconPath;
      localStorage.setItem(this.saveName, JSON.stringify(localS_iconPath));
    },
    // 选择icon
    handelSelect(item, index) {
      // if (item.indexOf("&") !== -1) {
      //   item = item.split(item.substring(item.lastIndexOf("&")))[0];
      // }
      this.currSelectIcon = item;
      this.selectIndex = index;
    },
    // 确认
    confirmSelectIcon() {
      if (!this.currSelectIcon) {
        this.$antdMessage.error({
          content: "获取图标异常，请刷新后再试！",
        });
        return;
      }
      this.$emit("uploadDataChange", { url: this.currSelectIcon });
      this.$refs.pickImgPopover.handleBlur();
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handelChange(file, fileList) {
      if (file.status == "ready") {
        // 判断用户是否登录
        // if (!this.$store.commit("user/checkUserIslogin", this)) return;
        if (this.timer) {
          clearTimeout(this.timer);
          this.timer = null;
        }

        this.timer = this.timeOutUpload();
      }
    },
    // 节流判断 upload组件 需要上传的文件 onchange是否已经结束
    timeOutUpload() {
      return setTimeout(() => {
        this.uploadFiles();
        clearTimeout(this.timer);
      }, 100);
    },
    // 上传文件
    async uploadFiles() {
      if (!this.userInfo.accessToken) {
        this.$router.push({
          name: "Login",
        });
        return;
      }
      let files = this.$refs.upload.uploadFiles;
      let uploadForm = new FormData();
      let hashArray = [];
      for (let item of files) {
        // 检查文件类型
        if (
          this.accept.indexOf(
            item.name.substring(item.name.lastIndexOf("."))
          ) === -1
        ) {
          this.$antdMessage.error({
            content: "此类型文件无法上传！",
          });
          return;
        }

        // 检查文件大小
        if (item.size > 1000000000) {
          this.$antdMessage.error({
            content: "上传文件最大为1Gb！",
          });
          return;
        }

        // 文件名
        let fileName = item.name;
        // 过滤英文分号
        if (item.name.indexOf(";") !== -1) {
          fileName = item.name.replace(/;/g, "；");
        }

        let hash = await encryptionToString(item);
        if (hash === "Fto5o-5ea0sNMlW_75VgGJCv2AcJ") {
          this.$antdMessage.error({
            content: "文件读取错误！",
          });
          return;
        }
        if (hash) hashArray.push(hash);

        // 校验通过的文件会放入formData内等待上传
        uploadForm.append("file", item.raw, fileName);
      }

      uploadForm.append(
        "courseInfo",
        JSON.stringify({
          userID: this.userInfo.userID,
          FileHashArray: JSON.stringify(hashArray), // 文件内容hash
        })
      );

      d_uploadmultifiles(uploadForm)
        .then((res) => {
          if (!res.data.filePaths.length) {
            this.$antdMessage.error({
              content: "上传失败",
            });
            return;
          }
          if (res) {
            // let fileUrl = res.split("上传成功！文件地址分别为：")[1];
            let fileUrl = res.data.filePaths;
            if (fileUrl) {
              // 将文件路径遍历 格式化并插入fileList
              fileUrl.forEach((item) => {
                item =
                  this.location +
                  item.split(item.substring(item.lastIndexOf("&")))[0];
                this.iconList.unshift(item);
                this.saveIconPathToLocalStorage(item);
              });
            }
          } else {
            this.$antdMessage.error({
              content: "上传失败！",
            });
          }
        })
        .catch((err) => console.log(err));
      // 清除文件列表中的文件
      this.$refs.upload.clearFiles();
    },
  },
};
</script>

<style lang="stylus">
.uploadComponent {
  .el-popover__reference-wrapper {
    .showImgBox {
      cursor: pointer;
      width: 100px;
      height: 100px;

      img {
        object-fit: cover;
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }

    .imgis-disabled {
      outline: none;
      cursor: not-allowed;
    }
  }
}

.selectImgListPopover {
  width: 500px;
  max-height: 498px;
  background-color: #ffffff;
  box-shadow: 0px 8px 16px 0px rgba(159, 178, 196, 0.3);
  border: solid 1px #9fa7b6;

  .popper__arrow {
    border-bottom-color: #9fa7b6 !important;
  }

  .imgList {
    .header {
      display: flex;
      justify-content: flex-start;

      .title {
        font-family: PMingLiU-ExtB;
        font-size: 16px;
        color: #333333;
      }

      .imgBox {
        width: 100px;
        height: 100px;

        img {
          object-fit: cover;
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }

      .courseImgBox {
        width: 123px;
        height: 61px;

        img {
          border-radius: 5px;
        }
      }

      .confirmBtn {
        flex: 1;
        margin-left: 20px;
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
      }
    }

    .iconList {
      margin-top: 20px;
      display: flex;
      flex-flow: row wrap;

      .uploadIcon {
        position: relative;
        cursor: pointer;
        margin-left: 5px;
        margin-top: 5px;
        width: 50px;
        height: 50px;
        border-radius: 2px;
        border: dashed 1px #a2c2e4;

        .upload-icon {
          width: 100%;
          height: 100%;

          .el-upload {
            width: 100%;
            height: 100%;
          }
        }
      }

      .uploadIcon:after {
        content: '';
        height: 2px;
        width: 30px;
        background: #1caffc;
        display: block;
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        border-radius: 10px;
        transform: translate(9px, 25px);
      }

      .uploadIcon:before {
        content: '';
        height: 30px;
        width: 2px;
        background: #1caffc;
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        border-radius: 10px;
        transform: translate(24px, 10px);
      }

      .iconBox {
        cursor: pointer;
        margin-left: 5px;
        margin-top: 5px;

        img {
          object-fit: cover;
          width: 50px;
          height: 50px;
        }
      }

      .is-selectIcon {
        box-shadow: 0px 0px 5px 1px rgba(111, 111, 111, 0.5);

        img {
          filter: drop-shadow(0px 0px 3px #111);
        }
      }
    }
  }
}
</style>
